<?php
// 数据库配置
$config = [
    'hostname' => 'localhost',
    'database' => 'api-mh',  // 请修改为您的数据库名
    'username' => 'root',     // 请修改为您的数据库用户名
    'password' => '123456',     // 请修改为您的数据库密码
    'charset'  => 'utf8mb4',
    'port'     => 3306,
];

try {
    // 连接数据库
    $dsn = "mysql:host={$config['hostname']};port={$config['port']};dbname={$config['database']};charset={$config['charset']}";
    $pdo = new PDO($dsn, $config['username'], $config['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);

    // 检查用户表是否存在测试用户
    $stmt = $pdo->prepare("SELECT * FROM users WHERE openid LIKE 'test_openid_%' LIMIT 1");
    $stmt->execute();
    $user = $stmt->fetch();

    if (!$user) {
        // 创建一个测试用户
        $stmt = $pdo->prepare("
            INSERT INTO user (openid, nickname, avatar, gender, city, agent_level, status, create_time, update_time) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $currentTime = date('Y-m-d H:i:s');
        $openid = 'test_openid_' . time();
        $stmt->execute([
            $openid,
            '测试用户',
            'https://example.com/avatar.jpg',
            1,
            '北京',
            1,
            1,
            $currentTime,
            $currentTime
        ]);
        
        $userId = $pdo->lastInsertId();
        
        echo json_encode([
            'success' => true,
            'message' => '测试用户创建成功',
            'user' => [
                'id' => $userId,
                'openid' => $openid
            ]
        ], JSON_UNESCAPED_UNICODE);
    } else {
        echo json_encode([
            'success' => true,
            'message' => '测试用户已存在',
            'user' => [
                'id' => $user['id'],
                'openid' => $user['openid']
            ]
        ], JSON_UNESCAPED_UNICODE);
    }
    
    // 提示访问token生成页面
    echo "\n\n";
    echo "请访问 /test_token.php?user_id=" . ($userId ?? $user['id']) . " 生成测试Token";
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => '错误: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
} 